<template>
  <div>
    <form action="/">
      <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" @focus='isShowResult=false' @search="onSearch" @cancel="$router.back()" />
    </form>
    <!-- 搜素结果 -->
    <search-result :searchText='searchText' v-if='isShowResult' />
    <!-- 联想建议 -->
    <search-suggestion @hehe='onSearch' :searchText='searchText' v-else-if='searchText' />

    <!-- 历史记录 -->
    <search-history @update-history=' history = $event' :search-history='history' @hehe='onSearch' v-else />
    <!-- @us='onSearch(Text)' -->
  </div>
</template>

<script>
import { setItem, getItem } from '@/utils/storage'
import SearchResult from './components/search-result.vue'
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import { mapState } from 'vuex'

export default {
  name: 'SearchIndex',
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult
  },
  data() {
    return {
      searchText: '',
      isShowResult: false,
      history: getItem('search-history') || []
    }
  },
  watch: {
    history() {
      setItem('search-history', this.history)
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    onSearch(text) {
      this.searchText = text
      const index = this.history.indexOf(text)
      if (index !== -1) {
        this.history.splice(index, 1)
      }
      this.history.unshift(text)

      this.isShowResult = true
    }
  }
}
</script>
<style lang="less" scoped>
.van-search {
  background-color: #2992ff;
  // box-sizing: border-box;
}
</style>
